import axios from 'axios'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
import { useUserStore } from '@/stores/userStore'
import router from '@/router/index'
const instance = axios.create({
  baseURL:'http://pcapi-xiaotuxian-front-devtest.itheima.net',
  timeout: 20000
})

// axios请求拦截器
instance.interceptors.request.use(config => {
  const userStore = useUserStore()
  const token = userStore.userData.token
  //console.log('请求拦截器');
  if(token){
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, e => Promise.reject(e))

// axios响应式拦截器
instance.interceptors.response.use(res => res.data, e => {
  ElMessage.error(e.response.data.message)
  //ElMessage.error(e.response.msg)
  const userStore = useUserStore()
  if(e.response.status===401){
    userStore.removeUserData()
    router.replace({path:'/login'})
  }
  return Promise.reject(e)
})

export default instance